<template>
  <div class="topicTable">
    <h2 style="margin-left: 675px;margin-bottom: 0;margin-top: 0">话题广场</h2>
    <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">新建话题</el-button>
    <hr style="width: 1450px;margin-left: 0"/>
    <div v-for="(topics,index) in topicTable" :key="index" :data="topics">
      <div>
        <el-row type="flex" justify="start">
          <div v-for="item in topics" :key="item.id" :data="item" style="width: 500px">
            <TopicContainer :topic="item">
              <template v-slot:operation1>
                <router-link :to="{path:'/BlogListView',query:{id:item.id}}">
                  <el-button type="primary" round style="width: 65px;margin-top: 2px;margin-right: 10px">进入</el-button>
                </router-link>
                <el-button type="danger" round style="width: 65px;margin-top: 2px;" @click="handleDelete(item)">删除</el-button>
              </template>
            </TopicContainer>
          </div>
        </el-row>
      </div>

    </div>

    <pagination v-show="total > 0"
                :total="total" :page.sync="queryParams.pageNum"
                :page-sizes="[10]" :layout="'prev, pager, next'"
                :limit.sync="queryParams.pageSize" @pagination="getTopicPage"
    />
    <el-dialog :visible.sync="open" width="500px" append-to-body @close="$refs['form'].resetFields()">
      <el-form ref="form" :model="form" label-width="100px" :rules="topicRules">
        <el-form-item label="话题名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入话题名称"/>
        </el-form-item>
        <el-form-item label="话题介绍" prop="introduce">
          <TextareaLimit :textAreaValue="form.introduce" v-model="form.introduce"></TextareaLimit>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {createTopic, listTopic, pageTopic, updateTopic,deleteTopic} from "@/api/topic";
import TopicContainer from "@/views/blog/TopicContainer";
import SearchBox from "@/views/reservation/search";
import Pagination from "@/components/Pagination/index";
import TextareaLimit from "@/components/TextareaLimit";

export default {
  name: "TopicList",
  components: {
    TextareaLimit,
    SearchBox, TopicContainer, Pagination
  },
  data() {
    return {
      open: false,
      topicList: [],
      topicTable: null,
      queryParams: {
        pageNum: 1,
        pageSize: 9,
      },
      total: 0,
      loading: false,
      form: {
        introduce: "",
        name: "",
      },
      topicRules: {
        name: [{required: true}, {max: 10, message: "话题名称长度不能超过10位"}],
      },
    }
  },
  created() {
    this.getTopicPage(this.queryParams)
  },
  methods: {
    getTopicList() {
      listTopic()
        .then((response) => {
          if (response.success) {
            this.topicList = response.data
          }
        }).catch((e) => {
        _this.$message.error(e, "出现未知错误");
      })
    },
    getTopicPage(data) {
      this.loading = true;
      pageTopic(data)
        .then((response) => {
          if (response.success) {
            this.topicList = response.data.records;
            this.topicTable = this.topicList.flatMap(((value, index, array) => {
                if (index % 3 === 0) {
                  return [array.slice(index, index + 3)]
                }
                return []
              }
            ))
            if (this.total === 0) {
              this.total = response.data.total;//重要，会决定有几个页码按钮
            }
            this.loading = false;
          }
        }).catch((e) => {
        _this.$message.error(e, "出现未知错误");
      })
    },
    // 新增按钮
    handleAdd() {
      this.open = true;
    },
    handleDelete(row){
      deleteTopic({id:row.id})
      .then((response=>{
          if(response.success){
            this.$alert("删除成功", {
              confirmButtonText: "确认",
              callback: (action) => {
                this.$router.go(0)
              },
            });
          }
        })
      )
    },
    handleCancel() {
      this.open = false;
      this.form =
        {
          introduce: "",
          name: "",
        };
    },
    add(data){
      createTopic(data)
    },
    submitForm: function () {
      // alert(this.form.introduce)
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateTopic(this.form)
              .then((response) => {
                if (response.success) {
                  this.$alert("修改成功", {
                    confirmButtonText: "修改成功",
                    callback: (action) => {
                      // console.log('请检查后重新输入')
                    },
                  });
                  this.open = false;
                  this.queryParams.pageNum=1
                  this.getTopicPage(this.queryParams)
                } else {
                  throw new Error("出现错误", response.message);
                }
              })
              .catch((e) => {
                this.$alert("出现错误", {
                  confirmButtonText: e + "\n" + "请检查后重新输入",
                  callback: (action) => {
                    console.log("请检查后重新输入");
                  },
                });
              });
          } else {
            createTopic(this.form)
              .then((response) => {
                if (response.success) {
                  this.$alert("新增成功", {
                    confirmButtonText: "确认",
                    callback: (action) => {
                      // console.log('请检查后重新输入')
                    },
                  });
                  this.open = false;
                  this.queryParams.pageNum=1
                  this.getTopicPage(this.queryParams)
                } else {
                  throw new Error("出现错误", response.message);
                }
              })
              .catch((e) => {
                this.$alert("出现错误", {
                  confirmButtonText: e + "\n" + "请检查后重新输入",
                  callback: (action) => {
                    console.log("请检查后重新输入");
                  },
                });
              });
          }
        }
      });
    },
  }
}
</script>
<style lang="scss">
.postTable {

}
</style>
